<template>
  <view class="course-container">
    <!-- 标题和更多按钮 -->
    <view class="course-header" v-if="headerDisplay">
      <text class="course-title">精品课程</text>
      <view class="more-btn" @click="jumpCategories">
        <text>更多</text>
        <image class="more" :src="IMAGE_CONFIG.more"></image>
        <!--        <u-icon name="arrow-right" size="18" color="#999"></u-icon>-->
      </view>
    </view>
    <!-- 年龄标签和课程分类标签 -->
    <scroll-view class="scroll-x" scroll-x>
      <view class="tag-container">
        <view v-for="(age, index) in ageTags" :key="index">
          <view class="tag-item" :class="['tag-age', ageIndex===index?'active' : '']" @click="selectAge(age,index)"
                v-if="age.isShow">
            {{ age.name }}
          </view>
        </view>
      </view>
    </scroll-view>
    <!-- 年龄标签和课程分类标签 -->
    <scroll-view class="scroll-x" scroll-x>
      <view class="tag-container" v-for="(category, index) in categoryTags" :key="index">
        <!--      <view v-for="(categorys, indexs) in category.childList" :key="indexs">-->
        <view class="tag-item" :class="['tag-age', categoryIndex===index?'active' : '']"
              @click="selectCategory(category.id,index)" v-if="category.isShow">
          {{ category.name }}
        </view>
        <!--      </view>-->
      </view>
    </scroll-view>
    <!-- 课程列表 -->
    <view class="course-list">
      <view class="course-item" v-for="(course, index) in courses" :key="index">
        <view class="course-img" @click="jumpDetails(course.id)">
          <image :src="course.image" mode="aspectFill"></image>
          <view class="course-type-tag" :class="course.productValue['默认'].type === 0 ? 'offline' : 'online'">
            <image class="type-icon" :src="course.productValue['默认'].type === 0 ? IMAGE_CONFIG.xianXia : IMAGE_CONFIG.xianShang"></image>
            <text class="type-text">{{ course.productValue['默认'].type === 0 ? '线下课' : '线上课' }}</text>
          </view>
        </view>
        <view class="course-info">
          <text class="course-name" @click="jumpDetails(course.id)">{{ course.name }}</text>
          <text class="course-studied" @click="jumpDetails(course.id)">
            {{ Math.floor(course.sales) + Math.floor(course.ficti) || 0 }}人学过
          </text>
          <view class="course-price">
            <text class="price-text">¥{{ course.price }}</text>
            <button class="buy-btn" type="default" @click="goBuy(course)">购买课程</button>
          </view>
        </view>
      </view>
    </view>
    <view class='loadingicon acea-row row-center-wrapper' style="color: #8F4C38">
      <text class='loading iconfont icon-jiazai'
            :hidden='loading==false'></text>
      {{ courses.length > 0 ? loadTitle : '暂无更多课程' }}
    </view>
  </view>
</template>

<script>

import {featureList, getCategoryList} from "../../api/product";
import {getMerProListApi} from "../../api/merchant";
import {
  Debounce
} from "@/utils/validate.js";
import {postCartAdd} from "@/api/product";
import {onGetPreOrder} from "@/libs/order";
import {
  ProductMarketingTypeEnum,
} from "@/enums/productEnums";
import {IMAGE_CONFIG} from '@/utils/imageConfig'
import {mapGetters} from "vuex";
import {toLogin} from "@/libs/login.js";

export default {
  name: 'classification',
  props: ['headerDisplay'],
  data() {
    return {
      IMAGE_CONFIG: IMAGE_CONFIG.index,
      ageTags: [],
      categoryTags: [],
      courses: [],
      categoryIndex: 0,
      categorysIndex: 0,
      ageIndex: 0,
      loadend: false,
      loadTitle: '加载更多',
      where: {
        keyword: '',
        priceOrder: '',
        salesOrder: '',
        //news: 0,
        page: 1,
        limit: 10,
        cid: '', //商城使用
        merId: '',
        cids: '' //商户使用
      },
      keyword: '',
      loading: false,
      cid: undefined,
      productValue: [], //系统属性
      attrValue: "", //已选属性
      attr: {
        cartAttr: false,
        productAttr: [],
        productSelect: {},
      },
      productInfo: {},
    };
  },
  onLoad: function (options) {
    this.merId = options.merId ? Number(options.merId) : 0;
    this.$set(this, 'keyword', options.searchValue || '');
  },
  mounted() {
    this.getTitList()
  },
  computed: {
    ...mapGetters(["isLogin", 'uid']),
  },
  methods: {
    jumpDetails(id) {
      if (this.isLogin === false) {
        toLogin();
      } else {
        uni.navigateTo({
          url: '/pages/discover/courseDetails/index?id=' + id
        })
      }
    },
    jumpCategories() {
      console.log(11)
      uni.switchTab({url: '/pages/study/index'})
    },
    selectAge(age, index) {
      if (this.ageIndex === index) return; // 已选中不处理
      this.ageIndex = index;
      this.categoryTags = age.childList || [];
      this.categoryIndex = 0;
      // 选中第一个分类
      if (this.categoryTags.length && this.categoryTags[0].childList && this.categoryTags[0].childList.length) {
        this.selectCategory(this.categoryTags[0].childList[0].id, 0);
      } else if (this.categoryTags.length) {
        // 没有子分类，直接用第一个分类
        this.selectCategory(this.categoryTags[0].id, 0);
      } else {
        // 没有分类，清空课程
        this.courses = [];
      }
    },
    selectCategory(cid, index) {
      this.categoryIndex = index;
      this.cid = cid;
      this.where.page = 1;
      this.getList();
    }, /**
     * 立即购买的按钮触发
     */
    goBuy: Debounce(function (item) {
      if(item.isBuy && item.productValue['默认'].type === 5){
        return this.$util.Tips({
          title: '线上课程只能购买一次，不能重复购买',
        });
      }
      // goBuy:(function (e) {
      if (this.isLogin === false) {
        toLogin();
      } else {
        this.productInfo = item
        this.goCat(0);
      }
    }),
    /**
     * 加入购物车
     */
    goCat: function (num) {
      let that = this,
          productSelect = that.productValue[this.attrValue];
      //打开属性
      if (that.attrValue) {
        //默认选中了属性，但是没有打开过属性弹窗还是自动打开让用户查看默认选中的属性
        that.attr.cartAttr = !that.isOpen ? true : false;
      } else {
        if (that.isOpen) that.attr.cartAttr = true;
        else that.attr.cartAttr = !that.attr.cartAttr;
      }
      //只有关闭属性弹窗时进行加入购物车
      if (that.attr.cartAttr === true && that.isOpen === false)
        return (that.isOpen = true);
      //如果有属性,没有选择,提示用户选择
      if (
          that.attr.productAttr.length &&
          productSelect.stock === 0 &&
          that.isOpen === true
      )
        return that.$util.Tips({
          title: "产品库存不足，请选择其它",
        });
      if (num === 1) {
        let q = {
          productId: parseFloat(that.id),
          cartNum: parseFloat(that.attr.productSelect.cart_num),
          isNew: false,
          productAttrUnique: that.attr.productSelect !== undefined ?
              that.attr.productSelect.unique : that.productInfo.id,
        };
        postCartAdd(q)
            .then(function (res) {
              that.isOpen = false;
              that.attr.cartAttr = false;
              that.$util.Tips({
                title: "添加购物车成功",
                success: () => {
                  that.getCartCount(true);
                },
              });
            })
            .catch((res) => {
              that.isOpen = false;
              return that.$util.Tips({
                title: res,
              });
            });
      } else {
        this.getPreOrder();
      }
    },
    /**
     * 预下单
     */
    getPreOrder: function () {
      if (
          this.marketingType === ProductMarketingTypeEnum.Groupbuying &&
          this.attr.productSelect.cart_num > this.buyLimitNum
      ) {
        this.isOpen = false;
        return this.$util.Tips({
          title: "超出限购数量",
        });
      }
      if (this.attr.productSelect.cart_num < 1) {
        uni.showToast({
          title: "单次可购买商品数量范围为 1~99",
          icon: "none",
        });
      } else {
        let types = "";
        // switch (this.marketingType) {
        switch (0) {
          case ProductMarketingTypeEnum.Normal:
            if (this.productInfo.type === 4) {
              types = "video";
            } else {
              types = "buyNow";
            }
            break;
          case ProductMarketingTypeEnum.Seckill:
            types = "seckill";
            break;
          case ProductMarketingTypeEnum.Groupbuying:
            types = "group";
            break;
        }
        this.id = this.productInfo.id ? this.productInfo.id : "";
        onGetPreOrder(types, [{
          attrValueId: parseFloat(this.productInfo.productValue['默认'].id),
          // attrValueId: parseFloat('2678'),
          productId: parseFloat(this.productInfo.id),
          // productId: parseFloat('99'),
          productNum: parseFloat('1'),
          groupBuyActivityId: parseFloat(this.groupActivityId),
          groupBuyRecordId: 0,
        },]);
      }
      this.isOpen = false;
    },
    getTitList() {
      let that = this;
      getCategoryList().then(res => {
        that.ageTags = res.data;
        that.categoryTags = that.ageTags[0].childList
        that.cid = -2
        that.getList();
        console.log('分类:', that.ageTags)
      })
    },
    getList() {
      console.log("分类列表")
      let that = this;
      that.merId = 0
      if (that.merId > 0) that.where.merId = that.merId
      that.where.keyword = encodeURIComponent(that.keyword);
      if (that.cid === 0) {
        that.where.cid = '';
        that.where.cids = '';
      } else {
        if (this.merId > 0) {
          that.where.cids = that.cid
          that.where.cid = '';
        } else {
          that.where.cid = that.cid;
          that.where.cids = ''
        }
      }
      that.merId === 0 ? featureList(that.where).then(res => {
        let list = res.data.list;
        // let courses = that.$util.SplitArray(list, that.courses);
        let loadend = list.length < that.where.limit;
        that.loadend = loadend;
        that.loading = false;
        that.loadTitle = loadend ? '已全部加载' : '加载更多';
        // that.$set(that, 'courses', courses);
        console.log(this.courses.length)
        if(res.data.total>this.courses.length){
          this.courses = [...this.courses, ...res.data.list];
          that.$set(that.where, 'page', res.data.page + 1);
        }
        this.isShow = true
        // that.courses = list
        console.log(that.courses)
      }).catch(err => {
        that.loading = false;
        that.loadTitle = '加载更多'
      }) : getMerProListApi(that.where).then(res => {
        let list = res.data.list;
        // let courses = that.$util.SplitArray(list, that.courses);
        let loadend = list.length < that.where.limit;
        that.loadend = loadend;
        that.loading = false;
        that.loadTitle = loadend ? '已全部加载' : '加载更多';
        // that.$set(that, 'courses', courses);
        console.log(this.courses.length)
        if(res.data.total>this.courses.length){
          this.courses = [...this.courses, ...res.data.list];
          that.$set(that.where, 'page', res.data.page + 1);
        }
        this.isShow = true
        // that.courses = list
        console.log(that.courses)
      }).catch(err => {
        that.loading = false;
        that.loadTitle = '加载更多'
      })
      console.log(that.merId)
    }
  },

  onReachBottom() {
    if (this.productList.length > 0) {
      this.getList();
    }
  }
};
</script>

<style lang="scss" scoped>

$colorTit: #231917;
$colorContent: #53433F;


.course-container {
  margin-top: 80rpx;
  padding: 15px;
  background-color: #FCFAF6;
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;

  .course-title {
    font-size: 20px;
    /*font-weight: bold;*/
    color: $colorTit;
  }

  .more-btn {
    display: flex;
    align-items: center;
    color: #8F4C38;
    font-weight: bold;
    z-index: 999;

    .more {
      width: 16rpx;
      height: 24rpx;
      margin-top: 2px;
      margin-left: 12rpx;
    }
  }
}

.scroll-x {
  white-space: nowrap;

  .tag-container {
    display: inline-flex;
    //display: flex;
    //flex-wrap: wrap;
    margin-bottom: 8px;
    font-weight: bold;

    .tag-item {
      padding: 8px 15px;
      border-radius: 20px;
      margin-right: 10px;
      margin-bottom: 6px;
      background-color: #F5E1A7;
      color: $colorContent;
      font-size: 14px;
      cursor: pointer;
      display: inline-block;

      &.tag-age.active {
        background-color: #CC8437;
        color: white;
      }

      &.tag-category.active {
        background-color: #F5E1A7;
        color: $colorContent;
      }
    }
  }
}

.course-list {
  display: flex;
  flex-direction: column;
  min-height: 300rpx;
  /*font-weight: bold;*/

  .course-item {
    display: flex;
    align-items: center;
    background-color: white;
    border-radius: 10px;
    margin-bottom: 15px;
    overflow: hidden;
    padding: 15px;

    .course-img {
      width: 200rpx;
      height: 200rpx;
      margin-right: 15px;
      overflow: hidden;
      border-radius: 10px;
      position: relative;
      /* 课程类型标签样式 */
      .course-type-tag {
        position: absolute;
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        padding: 8rpx 16rpx;
        //border-radius: 20rpx;
        color: #fff;
        font-size: 22rpx;
        font-weight: 500;
        z-index: 10;

        &.offline {
          background: linear-gradient(135deg, #b3793b, #b3793b);
        }

        &.online {
          background: linear-gradient(135deg, #8e4c38, #8e4c38);
        }

        .type-icon {
          margin-right: 10rpx;
          width: 20rpx;
          height: 20rpx;
        }

        .type-text {
          font-size: 22rpx;
          font-weight: 500;
        }
      }
      image {
        width: 100%; /* 图片宽度撑满容器 */
        height: 100%; /* 图片高度撑满容器 */
        object-fit: cover; /* 图片等比缩放，填满容器，可能裁剪 */
      }
    }

    .course-info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 406rpx;

      .course-name {
        font-size: 16px;
        color: $colorTit;
        margin-bottom: 5px;
        white-space: nowrap;      /* 禁止换行 */
        overflow: hidden;         /* 超出部分隐藏 */
        text-overflow: ellipsis;  /* 显示省略号 */
      }

      .course-studied {
        font-size: 14px;
        color: $colorContent;
        margin-bottom: 5px;
      }

      .course-price {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price-text {
          font-size: 16px;
          color: #B33B15;
        }

        .buy-btn {
          padding: 5px 15px;
          border: none;
          border-radius: 12px;
          background-color: #8F4C38;
          color: white;
          font-size: 14px;
        }
      }
    }
  }
}

.iconfont {
  font-size: 26rpx;
  color: #999999;

}
</style>